package com.itic.mall.mobile.pay;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.framework.annotation.CheckLogin;
import com.itic.appbase.framework.type.OrderType;
import com.itic.appbase.framework.type.PayType;
import com.itic.appbase.framework.utils.IdGen;
import com.itic.mall.mobile.base.BaseMobileInterface;
import com.itic.mall.system.orders.detail.persistence.model.OrdersDetail;
import com.itic.mall.system.orders.detail.service.OrdersDetailService;
import com.itic.mall.system.users.usersmall.persistence.model.UsersMall;
import com.itic.mall.system.users.usersmall.service.UsersMallService;


@Controller
@RequestMapping(value="/mobile/banlance")
public class BanlancePayInterface extends BaseMobileInterface {
	
	@Autowired
	private OrdersDetailService ordersDetailService;
	@Autowired
	private UsersMallService usersMallService;
	
	@RequestMapping(value = "/pay")   
	@ResponseBody 
	@CheckLogin
	public Map<String, Object> pay(HttpServletRequest request,HttpServletResponse response,String orderNo){  
		String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
		Map<String,Object> resultMap = new HashMap<String,Object>();
		try{  
			 UsersMall usersMall = this.CurUsersMall(request);
			 double banlance = usersMall.getMoney()==null?0:usersMall.getMoney();
			 OrdersDetail ordersDetail = this.ordersDetailService.getOrdersDetailByOrderNo(orderNo);
			 double actualPay = ordersDetail.getActualPay()==null?0:ordersDetail.getActualPay();
			 OrderType orderType = OrderType.getOrderType(ordersDetail.getState());
			 if(banlance!=0 && banlance>=actualPay && orderType!=null && OrderType.Paying.getState().equals(orderType.getState())) {
				 banlance = banlance - actualPay ;
				 usersMall.setMoney(banlance);
				String result =  this.usersMallService.edit(usersMall);
				if(SUCCESS.equals(result)) {
					String payNo = IdGen.uuid();
					this.ordersDetailService.aliPaySuccess(ordersDetail.getOrderNo(), payNo, PayType.balance, new Date());
					errorCode = SUCCESS_ERROR_CODE;
		 		    errorMsg = SUCCESS_ERROR_MSG;
				}else {
					errorCode = PAY_FAILD_CODE;
			    	errorMsg = PAY_FAILD_MSG;
				}
			 }else {
				errorCode = BANLANCE_NOT_ENOUGH_CODE;
				errorMsg = BANLANCE_NOT_ENOUGH_MSG;
			 }
          }catch(Exception e){  
        	 errorCode = SERVER_ERROR_CODE;
 		     errorMsg = SERVER_ERROR_MSG;
        	 logException("BanlancePayInterface", "pay", e.toString(),"余额支付",e);
          } 
		resultMap.put(CODE, errorCode);
    	resultMap.put(MSG, errorMsg);
    	isCrrossDomain(response);
		return resultMap;
	}  
	
}
